/*
* $Id: AddPointOperation.cpp 336 2011-09-28 06:06:36Z volok-aleksej@yandex.ru $
*
* Copyright 2009-2011 by Volokitin Aleksey
* All rights reserved
*
*/
#include "Common/include.h"
#include "AddPointOperation.h"
#include "Threads/ComReader.h"
#include "Database/TransactManager.h"
#include "Database/Tables/PointsTable.h"
#include "Database/Tables/FieldValuesTable.h"

CAddPointOperation::CAddPointOperation(CTransactManager* pManager)
: m_pManager(pManager){}
CAddPointOperation::~CAddPointOperation(){}

std::tstring CAddPointOperation::ExecuteOperation(IDatabase* pDatabase, IReader* pReader){
	CPointsTable points;
	CFieldValuesTable fvalues;
	int size;
	pReader->ReadInt(size);
	int lenRead = 0;
	int idPoint;
	lenRead = pReader->ReadInt(idPoint);
	lenRead += pReader->ReadUTF(points.m_content.s_strName);
	std::tstring strNamePoint = points.m_content.s_strName;
	lenRead += pReader->ReadUTF(points.m_content.s_strNote);	
	int idRecord;
	lenRead += pReader->ReadInt(idRecord);
	if(idRecord != 0){
		points.m_content.s_nIdRecord = fvalues.GetMaxId(pDatabase) + 1;
		m_pManager->AddIDMap(CTransactManager::ID(CTransactManager::FIELD_VALUE, idRecord),
							points.m_content.s_nIdRecord);
	}
	points.SetValue(pDatabase);
	m_pManager->AddIDMap(CTransactManager::ID(CTransactManager::POINT, idPoint),
						points.m_content.s_nId);
	while(size > lenRead){
		lenRead += pReader->ReadInt(idRecord);
		fvalues.m_content.s_nId = m_pManager->GetRealId(
			CTransactManager::ID(CTransactManager::FIELD_VALUE, idRecord));
		lenRead += pReader->ReadUTF(fvalues.m_content.s_strName);
		lenRead += pReader->ReadUTF(fvalues.m_content.s_strValue);
		lenRead += pReader->ReadInt((int&)fvalues.m_content.s_type);
		fvalues.SetValue(pDatabase);
	}
	std::tstring strLog = ILanguageManager::GetLanguageManager()->GetString(ADD_POINT_LOG_ID);
	return strLog + _T(" ") + strNamePoint;
}

void CAddPointOperation::Free(){
	delete this;
}
